package com.zdzx.controller.admin.base;

import java.time.LocalDateTime;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zdzx.base.common.util.RedisUtil;
import com.zdzx.base.common.util.UserInfoUtil;
import com.zdzx.common.result.PageInfo;
import com.zdzx.common.result.PageUtil;
import com.zdzx.common.result.Result;
import com.zdzx.common.result.ResultCode;
import com.zdzx.common.result.ResultUtil;
import com.zdzx.common.util.Md5Util;
import com.zdzx.mapper.UserMapper;
import com.zdzx.mapper.UserRoleMapper;
import com.zdzx.model.service.base.param.EditUser;
import com.zdzx.model.service.base.result.UserInfo;
import com.zdzx.model.service.base.vo.Function;
import com.zdzx.model.service.base.vo.User;
import com.zdzx.model.service.base.vo.UserRole;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@Api(tags = "用户")
@RestController
@RequestMapping("/admin")
public class UserController {

	
	@Autowired
	private RedisUtil redisUtil;
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private UserRoleMapper userRoleMapper;
	
	@ApiOperation(value = "获取用户信息", notes = "")
	@GetMapping("/user/getUserInfo")
	public Result<UserInfo> getUserInfo(HttpServletRequest request){
		UserInfo loginInfo = UserInfoUtil.getLoginInfo(UserInfo.class, redisUtil, request);
		//loginInfo.setResouces(null);
		return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null, loginInfo);
	}
	
	@ApiOperation(value = "获取用户功能", notes = "")
	@GetMapping("/user/getFunction")
	public Result<List<Function>> getResouces(HttpServletRequest request){
		UserInfo loginInfo = UserInfoUtil.getLoginInfo(UserInfo.class, redisUtil, request);
		List<Function> resouces = loginInfo.getResouces();
		return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null, resouces);
	}
	
	@ApiOperation(value = "获取列表", notes = "") 
	@GetMapping("/user") 
	public Result<PageInfo<User>> list(
			@ApiParam("") @RequestParam(value = "pageNum", required = false)Integer pageNum,
			@ApiParam("") @RequestParam(value = "pageSize", required = false)Integer pageSize,
			@ApiParam("") @RequestParam(value = "realName", required = false)String realName,
			@ApiParam("") @RequestParam(value = "tenantId", required = false)String tenantId){
		if (pageNum == null || pageSize == null) {
			pageNum = 1;
			pageSize = 10;
		}
		Page<User> page=new Page<User>(pageNum, pageSize);
		QueryWrapper<User> queryWrapper=new QueryWrapper<User>();
		if(!StringUtils.isEmpty(realName))
		queryWrapper.eq("real_name", realName);
		if(!StringUtils.isEmpty(tenantId))
			queryWrapper.eq("tenant_id", tenantId);
		IPage<User> info = userMapper.selectPage(page, queryWrapper);
		if(info.getRecords()!=null&&info.getRecords().size()>0) {
			for(int i=0;i<info.getRecords().size();i++) {
				User user = info.getRecords().get(i);
				QueryWrapper<UserRole> queryUserRole=new QueryWrapper<UserRole>();
				queryUserRole.eq("user_id", info.getRecords().get(i).getId());
				List<UserRole> userRoles = userRoleMapper.selectList(queryUserRole);
				user.setUserRole(userRoles);
			}
		}
		PageInfo<User> data = PageUtil.data(info.getPages(), info.getCurrent(), info.getTotal(), info.getRecords());
		return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null, data);
	}
	
	@ApiOperation(value = "添加", notes = "") 
	@PostMapping("/user") 
	public Result<String> save(@RequestBody EditUser entity){
		User user=new User();
		BeanUtils.copyProperties(entity, user);
		if(!StringUtils.isEmpty(user.getPassword()))
			user.setPassword(Md5Util.hash(user.getPassword()));
		user.setCreateTime(LocalDateTime.now());
		QueryWrapper<User> queryWrapper=new QueryWrapper<User>();
		queryWrapper.select("id");
		queryWrapper.eq("account", entity.getAccount());
		List<User> list = userMapper.selectList(queryWrapper);
		if(list!=null&&list.size()>0) {
			return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "手机号已存在", null);
		}
		
		if(StringUtils.isEmpty(user.getPassword())) {
			user.setPassword(Md5Util.hash("123456"));
		}else {
			user.setPassword(Md5Util.hash(user.getPassword()));
		}
		user.setCreateTime(LocalDateTime.now());
		int rows = userMapper.insert(user);
		List<String> roles = entity.getRoles();
		if(roles!=null&&roles.size()>0) {
			for (String string : roles) {
				UserRole userRoleEntity=new UserRole();
				userRoleEntity.setRoleId(string);
				userRoleEntity.setUserId(user.getId());
				userRoleMapper.insert(userRoleEntity);
			}
		}
		return ResultUtil.data(rows>0?ResultCode.RESULT_SUCCESS.getCode():ResultCode.RESULT_ERROR.getCode(), null, null);
	}
	
	@ApiOperation(value = "修改", notes = "") 
	@PutMapping("/user")
	@Transactional(rollbackFor = Exception.class)
	public Result<String> edit(@RequestBody EditUser entity){
		User user=new User();
		BeanUtils.copyProperties(entity, user);
		user.setUpdateTime(LocalDateTime.now());
		int rows = userMapper.updateById(user);
		QueryWrapper<UserRole> wrapper=new QueryWrapper<UserRole>();
		wrapper.eq("user_id", entity.getId());
		userRoleMapper.delete(wrapper);
		List<String> roles = entity.getRoles();
		if(roles!=null&&roles.size()>0) {
			for (String string : roles) {
				UserRole userRoleEntity=new UserRole();
				userRoleEntity.setRoleId(string);
				userRoleEntity.setUserId(entity.getId());
				userRoleMapper.insert(userRoleEntity);
			}
		}
		return ResultUtil.data(rows>0?ResultCode.RESULT_SUCCESS.getCode():ResultCode.RESULT_ERROR.getCode(), null, null);
	}
	
	@ApiOperation(value = "删除", notes = "") 
	@DeleteMapping("/user/{userId}") 
	public Result<String> del(@PathVariable("userId")String userId){
		int rows = userMapper.deleteById(userId);
		return ResultUtil.data(rows>0?ResultCode.RESULT_SUCCESS.getCode():ResultCode.RESULT_ERROR.getCode(), null, null);
	}
}
